<?php
/**
 * Created by PhpStorm.
 * User: shaowei
 * Date: 2022/8/31
 * Time: 14:18
 */

namespace App\Datas;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Tools\FunTool;

class System
{
    const CHINA_IP_HASH = "CHINAIP"; //hash 存储国内ip段

    /**
     * 按设备ID获取设备信息
     * @param string $deviceId
     * @return null
     */
    public function getDevice(string $deviceId) {
        $info = DB::table('system_device')->where(['device_id' => $deviceId])->first();
        if (!$info) {
            return null;
        }
        return (array)$info;
    }


    /**
     * 设置设备信息
     * @param string $deviceId
     * @param string $channelId
     * @param string $vaid
     * @param string $aaid
     * @param string $oaid
     * @param string $imei
     * @param string $idfa
     * @param string $brand
     * @param string $model
     * @param string $pixelRatio
     * @param string $screenWidth
     * @param string $screenHeight
     * @param string $system
     * @param string $platform
     * @param string $version
     * @param string $sIP
     * @param string $sIPCountryCo
     * @return mixed
     */
	public function setDevice(string $deviceId, string $channelId, string $vaid, string $aaid, string $oaid, string $imei, string $idfa, string $brand, string $model, string $pixelRatio, string $screenWidth, string $screenHeight, string $system, string $platform, string $adCburl, string $adSource, string $version, string $appsflysid, string $sIP, $sIPCountryCo) {

        $installInfo = $this->getInstallInfo($appsflysid, $platform);

        $data = [
            'channel_id' => $channelId,
            'device_id' => $deviceId,
            'vaid' => $vaid,
            'aaid' => $aaid,
            'oaid' => $oaid,
            'imei' => $imei,
            'idfa' => $idfa,
            'brand' => $brand,
            'model' => $model,
            'pixel_ratio' => $pixelRatio,
            'screen_width' => $screenWidth,
            'screen_height' => $screenHeight,
            'system' => $system,
            'platform' => $platform,
            'ad_cburl' => $adCburl,
            'ad_source' => $adSource,
            'version' => $version,
            'appsfly_id' => $appsflysid,
            'ip' => $sIP,
            'country_co' => $sIPCountryCo,
            'install_time'=> $installInfo['install_time'] ?? '',
            'af_channel'=> $installInfo['media_source'] ?? '',
        ];
        return DB::table('system_device')->insert($data);
    }


    public function syncAppsflyid($deviceInfo, $appsflysid){
        $info = DB::table('af_log')->where('appsflyer_id',$appsflysid)->first();
        if ($info) {
           $content = json_decode($info->content, true);
           if (isset($content['install_time_selected_timezone'])) {
               $install_time = date('Y-m-d H:i:s',strtotime($content['install_time_selected_timezone']));
               DB::table('system_device')->where('id',$deviceInfo['id'])->update(['install_time'=>$install_time]);
           }
        }
    }


    public function getInstallInfo($appsflysid, $platform){
        $media_source = '';
        if ($appsflysid) {
            $info = DB::table('af_log')->where('appsflyer_id',$appsflysid)->first();
            if (!$info) {
                $install_time = FunTool::getReduceTime();
                $media_source = 'googleadwords_int';
            }else{
                $content = json_decode($info->content, true);
                if (isset($content['install_time_selected_timezone'])) {
                    $install_time = date('Y-m-d H:i:s',strtotime($content['install_time_selected_timezone']));
                }else{
                    $install_time = FunTool::getReduceTime();
                }
                $media_source = $content['media_source'];
                if ($platform == 'android') { //安卓的
                    if ($content['media_source'] == 'organic') {
                        $media_source = 'googleadwords_int';
                    }
                    if ($content['media_source'] == 'restricted') {
                        $media_source = 'Facebook Ads';
                    }
                }
            }
        }else{
            $media_source = 'googleadwords_int';
            $install_time = FunTool::getReduceTime();
        }

        return ['install_time'=>$install_time, 'media_source'=>$media_source];
    }


    public function setAdTag(string $tag, string $cburl, string $channel, string $source, string $os)
    {
        $key = 'AD:TAG:' . $tag;
        $data = [
            'channel' => $channel,
            'source' => $source,
            'os' => $os,
            'cburl' => $cburl,
        ];
        Redis::hmset($key, $data);
        Redis::EXPIRE($key, 3600*24);
    }

    public function getAdTag(string $tag)
    {
        $key = 'AD:TAG:' . $tag;
        return Redis::hgetall($key);
    }


    public function setFirstOpenNx($deviceId, $dtime) {
        $key = 'FIRSTOPEN:' . $deviceId;
        Redis::SETNX($key, time() - $dtime);
        Redis::EXPIRE($key, 3600*24*15);
        return true;
    }

    public function setFirstOpen($deviceId) {
        $key = 'FIRSTOPEN:' . $deviceId;
        Redis::SET($key, time());
        Redis::EXPIRE($key, 3600*24*3);
        return true;
    }


    public function getFirstOpen($deviceId) {
        $key = 'FIRSTOPEN:' . $deviceId;
        $ret = Redis::get($key);
        if (!$ret) {
            return time();
        }
        return intval($ret);

    }

    public function getHostSize() {
        $hostHashKey = 'painter:host';
        $hostKey = 'painter:host:';
        $hosts = Redis::HKEYS($hostHashKey);
        $size = 0;
        foreach ($hosts as $host) {
            if(Redis::EXISTS($hostKey.$host)) {
                $size++;
            }
        }
        return $size;
    }

    public function getQueueSize() {
        return Redis::LLEN('painter:queue1');
    }

    //判断一个ip是否属于china
    public function is_ip_in_china($ip) {
        $ip = trim($ip);
        $first_a = explode(".", $ip);
        if (!isset($first_a[0]) || $first_a[0] == "") {
            //ip有误，按国外算
            return false;
        }
        $first = $first_a[0];
        
        $arr_range = $this->hash_get(self::CHINA_IP_HASH, $first);
        if (!is_array($arr_range) || sizeof($arr_range) == 0) {
            return false;
        }

        if ($this->is_ip_in_arr_range($ip, $arr_range) == true) {
            return true;
        } else {
            return false;
        }
    }

    //判断一个ip是否属于ip的range数组
    public function is_ip_in_arr_range($ip, $arr_range) {
        $ip_long = (double) (sprintf("%u", ip2long($ip)));

        foreach ($arr_range as $k => $one) {
            $one = trim($one);
            //echo $one.":\n";
            $arr_one = explode("--", $one);

            if (!isset($arr_one[0]) || !isset($arr_one[1])) {
              continue;
            }

            $begin = $arr_one[0];
            $end = $arr_one[1];

            if ($ip_long >= $begin && $ip_long <= $end) {
                return true;
            }
        }
        return false;
    }

    //得到一个hash中对应key的value
    function hash_get($hash_name, $key_name) {
        $str = Redis::hget($hash_name, $key_name);
        $arr = json_decode($str,true);
        return $arr;
    }

	/**
	 * 设置AF ID
	 * @param string $deviceId
	 * @param string $appsflyid
	 * @return bool
	 */
	public function setAppsflyid(string $deviceId, string $appsflyid) {
		if(empty($deviceId)) {
			return false;
		}
        $updateArr = [];
        $updateArr['appsfly_id'] = $appsflyid;
        $afInfo = DB::table('af_log')->where('appsflyer_id',$appsflyid)->first();
        if ($afInfo) {
            $content = json_decode($afInfo->content, true);
            if (isset($content['install_time_selected_timezone'])) {
                $updateArr['install_time'] = date('Y-m-d H:i:s',strtotime($content['install_time_selected_timezone']));
            }
            $updateArr['af_channel'] = $content['media_source'];
            if ($afInfo->platform == 2) {//安卓的
                if ($content['media_source'] == 'organic') {
                    $updateArr['af_channel'] = 'googleadwords_int';
                }
                if ($content['media_source'] == 'restricted') {
                    $updateArr['af_channel'] = 'Facebook Ads';
                }
            }
        }
		$info = DB::table('system_device')->where(['device_id' => $deviceId])->update($updateArr);
		return true;
	}

    /**
     * 判断是否更改afid
     */
    public function checkAfidChange($deviceInfo){
        $payOrderAmount = DB::table('pay_order')->where('device_id',$deviceInfo['device_id'])->where('status',1)->count();
        if ($payOrderAmount > 0) {//不变更
            return false;
        }
        //没有付费记录的话，在判断用户自从激活后到现在是否超过三个月，超过就变更，不超过不变更
        $activeTime = date('Y-m-d', strtotime($deviceInfo['created_at']));
        $cha = time() - strtotime($activeTime);
        $day = ceil($cha/86400);
        if ($day >= 90) {
            return true;
        }else{
            return false;
        }
    }

	/**
	 * 更新设备信息
	 * @param string $sDeviceID
	 * @param array  $aUpdate
	 * @return bool
	 */
	public function updateDevice(string $sDeviceID, array $aUpdate) {
		if(empty($sDeviceID)){
			return  false;
		}
		$info = DB::table('system_device')->where(['device_id' => $sDeviceID])->update($aUpdate);
		return true;
	}
}